<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { 
    Bars3Icon, 
    ArrowUpIcon, 
    ArrowDownIcon,
    ClockIcon,
    BarsArrowUpIcon
} from '@heroicons/vue/20/solid'
import axios from 'axios'
import { useToast } from '@/Composables/useToast'

const props = defineProps({
    seriesId: {
        type: [Number, String, null],
        default: null
    },
    postId: {
        type: [Number, String, null],
        default: null
    },
    sortMode: {
        type: String,
        default: 'manual' // 'manual' 或 'published_at'
    },
    disabled: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(['update:sortMode', 'update:seriesOrder'])

const toast = useToast()
const posts = ref([])
const loading = ref(false)
const saving = ref(false)
const draggedIndex = ref(null)

// 加载系列文章
const loadPosts = async () => {
    if (!props.seriesId) {
        posts.value = []
        return
    }

    loading.value = true
    try {
        // 从系列详情 API 获取文章列表（后端已根据 sort_mode 排序）
        const response = await axios.get(route('api.series.show', props.seriesId))
        const series = response.data
        
        // 后端返回的 posts 字段包含已排序的文章列表
        if (series.posts && Array.isArray(series.posts)) {
            posts.value = series.posts
        } else {
            // 如果没有 posts 字段，尝试从其他地方获取
            posts.value = []
        }
    } catch (error) {
        console.error('加载系列文章失败:', error)
        toast.error('加载系列文章失败')
        posts.value = []
    } finally {
        loading.value = false
    }
}

// 拖拽开始
const handleDragStart = (index) => {
    if (props.disabled || props.sortMode !== 'manual') return
    draggedIndex.value = index
}

// 拖拽结束
const handleDragEnd = () => {
    draggedIndex.value = null
}

// 拖拽进入
const handleDragEnter = (index) => {
    if (props.disabled || props.sortMode !== 'manual' || draggedIndex.value === null) return
    
    if (draggedIndex.value !== index) {
        const newPosts = [...posts.value]
        const [removed] = newPosts.splice(draggedIndex.value, 1)
        newPosts.splice(index, 0, removed)
        posts.value = newPosts
        draggedIndex.value = index
    }
}

// 保存顺序
const saveOrder = async () => {
    if (!props.seriesId || props.sortMode !== 'manual') return

    saving.value = true
    try {
        const postOrders = {}
        posts.value.forEach((post, index) => {
            postOrders[post.id] = index + 1
        })

        await axios.post(route('api.series.update-order', props.seriesId), {
            post_orders: postOrders
        })

        toast.success('文章顺序已保存')
        emit('update:seriesOrder', postOrders)
    } catch (error) {
        console.error('保存文章顺序失败:', error)
        toast.error(error.response?.data?.message || '保存文章顺序失败')
    } finally {
        saving.value = false
    }
}

// 切换排序模式
const toggleSortMode = async () => {
    if (!props.seriesId || props.disabled) return

    const newMode = props.sortMode === 'manual' ? 'published_at' : 'manual'
    
    try {
        await axios.post(route('api.series.update-sort-mode', props.seriesId), {
            sort_mode: newMode
        })
        
        emit('update:sortMode', newMode)
        toast.success('排序模式已更新')
        
        // 重新加载文章
        await loadPosts()
    } catch (error) {
        console.error('更新排序模式失败:', error)
        toast.error(error.response?.data?.message || '更新排序模式失败')
    }
}

// 监听 seriesId 变化
watch(() => props.seriesId, () => {
    loadPosts()
}, { immediate: true })

// 监听 sortMode 变化
watch(() => props.sortMode, () => {
    loadPosts()
})
</script>

<template>
    <div v-if="seriesId" class="space-y-4">
        <!-- 排序模式切换 -->
        <div class="flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <span class="text-sm font-medium text-gray-700 dark:text-gray-300">
                    排序模式：
                </span>
                <button
                    @click="toggleSortMode"
                    :disabled="disabled"
                    type="button"
                    class="inline-flex items-center px-3 py-1.5 border border-gray-300 dark:border-gray-600 rounded-md text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    <BarsArrowUpIcon v-if="sortMode === 'manual'" class="h-4 w-4 mr-1" />
                    <ClockIcon v-else class="h-4 w-4 mr-1" />
                    {{ sortMode === 'manual' ? '手动排序' : '按发布时间' }}
                </button>
            </div>
            <button
                v-if="sortMode === 'manual' && !disabled"
                @click="saveOrder"
                :disabled="saving"
                type="button"
                class="inline-flex items-center px-3 py-1.5 border border-transparent rounded-md text-sm font-medium text-white bg-orange-600 hover:bg-orange-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
                {{ saving ? '保存中...' : '保存顺序' }}
            </button>
        </div>

        <!-- 文章列表 -->
        <div v-if="loading" class="text-center text-gray-500 dark:text-gray-400 py-4">
            加载中...
        </div>
        <div v-else-if="posts.length === 0" class="text-center text-gray-500 dark:text-gray-400 py-4">
            该系列还没有文章
        </div>
        <div v-else class="space-y-2">
            <div
                v-for="(post, index) in posts"
                :key="post.id"
                :draggable="sortMode === 'manual' && !disabled"
                @dragstart="handleDragStart(index)"
                @dragend="handleDragEnd"
                @dragover.prevent
                @dragenter.prevent="handleDragEnter(index)"
                :class="[
                    'flex items-center space-x-3 p-3 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg',
                    sortMode === 'manual' && !disabled && 'cursor-move hover:bg-gray-50 dark:hover:bg-gray-700',
                    draggedIndex === index && 'opacity-50'
                ]"
            >
                <!-- 拖拽手柄 -->
                <div v-if="sortMode === 'manual' && !disabled" class="text-gray-400">
                    <Bars3Icon class="h-5 w-5" />
                </div>
                
                <!-- 序号 -->
                <div class="flex-shrink-0 w-8 h-8 flex items-center justify-center rounded-full bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-300 text-sm font-medium">
                    {{ index + 1 }}
                </div>

                <!-- 文章信息 -->
                <div class="flex-1 min-w-0">
                    <div class="font-medium text-gray-900 dark:text-white truncate">
                        {{ post.title }}
                    </div>
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                        {{ new Date(post.published_at).toLocaleDateString('zh-CN') }}
                    </div>
                </div>

                <!-- 当前文章标识 -->
                <div v-if="post.id === parseInt(postId)" class="flex-shrink-0">
                    <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-300">
                        当前文章
                    </span>
                </div>
            </div>
        </div>

        <!-- 提示信息 -->
        <div v-if="sortMode === 'manual' && !disabled" class="text-xs text-gray-500 dark:text-gray-400">
            提示：拖拽文章可以调整顺序，调整后请点击"保存顺序"按钮
        </div>
    </div>
    <div v-else class="text-sm text-gray-500 dark:text-gray-400">
        请先选择一个系列
    </div>
</template>

